package com.lottery.web.controller;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.lottery.common.dto.CqsscDTO;
import com.lottery.common.exception.BIZException;
import com.lottery.common.util.EhCacheUtils;
import com.lottery.common.util.PropertiesUtil;
import com.lottery.cqssc.service.CqsscService;

/**
 * 
 * @描述: 定义主页公共接口
 *
 * @author LiBing
 * @date 2016年10月29日 上午10:45:46
 *
 */
@Controller
@RequestMapping("/main")
public class MainPageController extends BaseController {
	private static Logger logger = Logger.getLogger(MainPageController.class);

	@Resource
	private CqsscService qsscService;

	@RequestMapping("/cqssc/lastest")
	@ResponseBody
	public String cqsscLastestOpencode() {
		logger.info("begin to query cqssc lastest opencode.");
		
		try {
			//1.查询缓存
			String lastest = (String)EhCacheUtils.get("cqssc_lastest");
			
			if(StringUtils.isBlank(lastest)){
				//2. 查询数据库
				HashMap<String,String> lastestMap = new HashMap<String,String>();
				CqsscDTO cqsscDto = qsscService.queryLastestCqssc();
				lastestMap.put("expect",cqsscDto.getExpect());
				lastestMap.put("openCode", cqsscDto.getOpencode());
				lastest = this.jsonResult(lastestMap);
			}
			return lastest;
		} catch (BIZException e) {
			logger.error("cqsscLastestOpencode ", e);
			return errorResult("cqsscLastestOpencode exception.");
		}
	}
	
	@RequestMapping(value = "/getOptLeftTime", method = RequestMethod.POST)
	@ResponseBody
	public String getLeftTime(@RequestParam(value = "gameType", required = false) String gameType,
							HttpServletRequest request, HttpServletResponse response) {
		logger.info("begin to get opt left time, param is: " + gameType);
		long optLeftTime = 1000;
		
		try {
			long optInterval = Long.parseLong(this.getTimeIntervalFromProperties(""));
			CqsscDTO sqsscDto = this.getLastestCqsscDTOFromDB();
			long openTimestamp = Long.parseLong(sqsscDto.getOpentimestamp());
			long currentTimestamp = new Date().getTime();
			optLeftTime = openTimestamp + optInterval - currentTimestamp / 1000;
		} catch (Exception e) {
			logger.error("getOptLeftTime: " + e.getMessage());
		}
		
		Map<String, Object> leftTimeMap = new HashMap<String, Object>();
		leftTimeMap.put("optLeftTime", optLeftTime);
		String leftTimeStr = this.jsonResult(leftTimeMap);
		logger.info("getOptLeftTime: " + leftTimeStr);
		
		return leftTimeStr;
	}

	@RequestMapping(value = "/getOpenLeftTime", method = RequestMethod.POST)
	@ResponseBody
	public String getOpenLeftTime(@RequestParam(value = "gameType", required = false) String gameType,
								HttpServletRequest request, HttpServletResponse response) {
		logger.info("begin to get open left time, param is: " + gameType);
		long openLeftTime = 2 * 60;
		
		try {
			long optInterval = Long.parseLong(this.getTimeIntervalFromProperties(""));
			long openInterval = Long.parseLong(PropertiesUtil.getDefaulSystemProperties().getProperty("lotter.result.time"));
			CqsscDTO cqsscDTO = this.getLastestCqsscDTOFromDB();
			long openTimestamp = Long.parseLong(cqsscDTO.getOpentimestamp());
			long currentTimestamp = (long) (new Date().getTime() * 0.001);
			openLeftTime = openTimestamp + optInterval + openInterval - currentTimestamp;
		} catch (Exception e) {
			logger.error("getOpenLeftTime: " + e.getMessage());
		}
		
		Map<String, Object> openLeftTimeMap = new HashMap<String, Object>();
		openLeftTimeMap.put("openLeftTime", openLeftTime);
		String openLeftTimeStr = this.jsonResult(openLeftTimeMap);
		logger.info("getOpenLeftTime: " + openLeftTimeStr);
		
		return openLeftTimeStr;
	}
	
	private CqsscDTO getLastestCqsscDTOFromDB() {
		CqsscDTO sqsscDTO = this.qsscService.queryLastestCqssc();
		return sqsscDTO;
	}
	
	private String getTimeIntervalFromProperties(String gameType) {
		String interval = StringUtils.EMPTY;
		Calendar today = Calendar.getInstance();
		Calendar todayAtEightClock = Calendar.getInstance();
		todayAtEightClock.set(Calendar.HOUR_OF_DAY, 8);
		todayAtEightClock.set(Calendar.MINUTE, 0);
		todayAtEightClock.set(Calendar.SECOND, 0);
		Calendar todayAtTwentyClock = Calendar.getInstance();
		todayAtTwentyClock.set(Calendar.HOUR_OF_DAY, 20);
		todayAtTwentyClock.set(Calendar.MINUTE, 0);
		todayAtTwentyClock.set(Calendar.SECOND, 0);
		logger.info("today: "+ today.getTime() + "  8 clock: " + todayAtEightClock.getTime() + 
				" 20 clock: " + todayAtTwentyClock.getTime());
		if (today.getTimeInMillis() >= todayAtEightClock.getTimeInMillis() &&
			today.getTimeInMillis() <= todayAtTwentyClock.getTimeInMillis()) {
			interval = PropertiesUtil.getDefaulSystemProperties().getProperty("day.time.interval");
		} else {
			interval = PropertiesUtil.getDefaulSystemProperties().getProperty("night.time.interval");
		}
		logger.info("interval: " + interval);
		return interval;
	}
	
	@RequestMapping(value = "/test_getOptLeftTime", method = RequestMethod.POST)
	@ResponseBody
	public void getOptLeftTime(HttpServletRequest request, HttpServletResponse response) {
		String gameType = request.getParameter("gameType");
		HttpSession session = request.getSession();
		logger.info("begin to get opt left time, param is: " + gameType);
		long leftTime = 0;
		
		try {
			if (session == null) {
				String contextPath = request.getContextPath();
				response.sendRedirect(contextPath + "/static/layout/login.jsp");
			}
			
			while (true) {
				System.out.println("leftTime: " + leftTime);
				try {
					Thread.sleep(1000);
					if (leftTime-- < 0) {
						leftTime = calcualteLeftTime();
					}

					logger.info("leftTime: " + leftTime);
					writeResponse(response, String.valueOf(leftTime), "showLeftTime");
				} catch (Exception e) {
					logger.info(e);
				}
			}
		} catch (Exception e) {
			logger.error("getOptLeftTime: " + e.getMessage());
		}
	}
	
	private void writeResponse(HttpServletResponse response, String leftTime, String clientMethod) throws Exception {
        StringBuffer sb = new StringBuffer();  
        sb.append("<script type=\"text/javascript\">//<![CDATA[\n");  
        sb.append("     parent.window.gameCode.").append(clientMethod).append("(\"").append(leftTime).append("\");\n");  
        sb.append("//]]></script>");  
        logger.info(sb.toString());  
  
        response.setContentType("text/html;charset=UTF-8");  
        response.addHeader("Pragma", "no-cache");  
        response.setHeader("Cache-Control", "no-cache,no-store,must-revalidate");  
        response.setHeader("Cache-Control", "pre-check=0,post-check=0");  
        response.setDateHeader("Expires", 0);  
        response.getWriter().write(sb.toString());  
        response.flushBuffer();  
        return;
	}
	
	public long calcualteLeftTime() {
		long optInterval = Long.parseLong(this.getTimeIntervalFromProperties(""));
		CqsscDTO sqsscDto = this.qsscService.queryLastestCqssc();
		long openTimestamp = Long.parseLong(sqsscDto.getOpentimestamp());
		long currentTimestamp = new Date().getTime();
		long optLeftTime = openTimestamp + optInterval - currentTimestamp / 1000;
		
		return optLeftTime;
	}
	
}
